package com.ay.weixin.fdc.boss.kanfang.event;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.util.ExcelUtils;
import org.lizar.util.StringHelper;
import org.lizar.util.pager.PageData;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.FDCProjectStatus;
import com.ay.weixin.config.types.KanFangProgress;
import com.ay.weixin.config.types.KanFangStatus;
import com.ay.weixin.config.types.KanFangType;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangDao;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangFlowDao;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFang;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFangDetail;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFangFlow;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.FDCAgentDetail;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.CashFlow;
import com.ay.weixin.mail.domain.Email;
import com.ay.weixin.templatereply.domain.ReplyMsg;
import com.ay.weixin.templatereply.domain.TemplateReply;

/**
 * 

 * 
 * */
public class KanFangMC extends Event implements Before {
	
	private static IbatisKanFangDao		kanfang_dao;
	private CategoryLoader				cl;
	private IbatisProjectDao			project_dao;
	private static IbatisKanFangFlowDao	kanfang_flow_dao;
	private static IbatisCashFlow		cash_flow_dao;
	private static FDCAgentDao			fdcuser_dao;
	private UserDao						user_dao;
	private static WeiXinInfoDao		weixin_dao;
	
	@Override
	public void init_property() throws Exception {
		kanfang_dao = Container.get(IbatisKanFangDao.class);
		project_dao = Container.get(IbatisProjectDao.class);
		cl = Container.get(CategoryLoader.class);
		kanfang_flow_dao = Container.get(IbatisKanFangFlowDao.class);
		cash_flow_dao = Container.get(IbatisCashFlow.class);
		fdcuser_dao = Container.get(FDCAgentDao.class);
		user_dao = Container.get(UserDao.class);
		weixin_dao = Container.get(WeiXinInfoDao.class);
		
	}
	
	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("mc_user_enable_salesman", ProjectConfig.getBool(wxproject_id,"fdc_usercenter.enable_salesman"));
	}
	
	@Override
	public String default_handling_path() {
		return "/mc/fdc/kanfang/*";
	}
	
	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer cus = (Customer) el.getSessionAttr("customer");
		if (cus == null) {
			el.response_to_root(CustomerLogin.login_path());
		} else {
			if (el.queryPathCheck(3, "")) {
				index(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "update")) {
				update(el,cus);
			} else if (el.queryPathCheck(3, "view_setting")) {
				view_setting(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "setting")) {
				setting(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "batch_outport")) {
				batch_outport(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "user_detail")) {
				user_detail(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "sales_detail")) {
				sales_detail(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "batch_import_submit")) {
				batch_import_submit(el,cus.getWxprojectID());
			} else if (el.queryPathCheck(3, "batch_import")) {
				batch_import_view(el);
			}
		}
	}
	
	private void batch_outport(EventLoader el,long wxproject_id) throws IOException, ServletException {
		String name = el.param("name", "", "utf-8");
		String phone = el.getStr("phone");
		String whereCondition = buildWhereCondition(el);
		List<KanFangDetail> list = null;
		try {
			if (StringHelper.isNull(name) && StringHelper.isNull(phone)) {
				list = kanfang_dao.getByWhereCondition(wxproject_id,whereCondition);
			} else if (StringHelper.isNotNull(name)) {
				list = kanfang_dao.searchAllByWhereCondition(wxproject_id,whereCondition, name);
			} else if (StringHelper.isNotNull(phone)) {
				list = kanfang_dao.searchAllByWhereConditionAndContact(wxproject_id,whereCondition, name);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if (list == null) {
			list = new LinkedList<KanFangDetail>();
		}
		
		List<FDCProject> project_list = null;
		
		try {
			project_list = project_dao.getAllByWxprojectId(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error") + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if (project_list != null) {
			for (KanFangDetail kanfang : list) {
				for (FDCProject project : project_list) {
					if (project.getId() == kanfang.getProject_id()) {
						kanfang.setProject_name(project.getTitle());
						break;
					}
				}
			}
		}
		
		List<List<String>> data = new LinkedList<List<String>>();
		List<String> titles = new LinkedList();
		data.add(titles);
		
		titles.add("客户名称");
		titles.add("类型");
		titles.add("联系电话");
		titles.add("推荐人");
		titles.add("推荐时间");
		titles.add("看房日期");
		titles.add("状态");
		titles.add("进度");
		titles.add("是否支付到访奖金");
		titles.add("是否支付佣金");
		titles.add("到访奖金");
		titles.add("佣金");
		titles.add("备注");
		titles.add("近期更新");
		titles.add("项目名称");
		for (KanFangDetail kanfang : list) {
			List<String> row = new LinkedList();
			row.add(kanfang.getName());
			row.add(KanFangType.getStatus(kanfang.getType()).getDesc());
			row.add(kanfang.getContact());
			row.add(kanfang.getRecommend_user_name());
			row.add(kanfang.getCreate_time_str());
			row.add(kanfang.getGohousedate());
			row.add(KanFangStatus.getDesc(kanfang.getStatus()));
			row.add(KanFangProgress.getStatus(kanfang.getProgress()).getDesc());
			if (kanfang.getOn_visit_paid() == KanFang.ON_VISIT_PAID) {
				row.add("已支付");
			} else {
				row.add("未支付");
			}
			if (kanfang.getRecommend_paid() == KanFang.RECOMMEND_PAID) {
				row.add("已支付");
			} else {
				row.add("未支付");
			}
			row.add(kanfang.getVisit_paid() + "");
			row.add(kanfang.getCommission() + "");
			row.add(kanfang.getRemark());
			row.add(kanfang.getUpdate_date().toLocaleString());
			row.add(kanfang.getProject_name());
			data.add(row);
		}
		el.response().setContentType("application/vndms-excel");
		
		File output = new File(el.getRealPath("/upload/xls/cache"));
		if (!output.exists()) {
			output.mkdirs();
		}
		File file = new File(el.getRealPath("/upload/xls/cache/kanfang.xls"));
		
		ExcelUtils.writeExcel("看房客户信息", data, file);
		
		el.response_to_root("/upload/xls/cache/kanfang.xls");
	}
	
	private void batch_import_view(EventLoader el) throws IOException, ServletException {
		el.template("/WEB-INF/template/boss/fdc/kanfang/batch_import.vm");
	}
	
	private void batch_import_submit(EventLoader el,long wxproject_id) throws IOException, ServletException {
		FilePostForm form = el.parseFilePostForm(500 * 1024 * 1024);
		if (StringHelper.isNotNull(form.getErrorMsg())) {
			el.setAttr("msg", form.getErrorMsg());
			batch_import_view(el);
			return;
		}
		FileItem file_item = form.getFileItem(0);
		if (file_item == null) {
			el.setAttr("msg", el.i18("mc.fdc.kanfang.file.is.empty"));
			batch_import_view(el);
			return;
		}
		List<List<String>> kanfang_list = ExcelUtils.readExcel(file_item.getInputStream(), 1);
		
		if (kanfang_list.isEmpty()) {
			el.setAttr("msg", el.i18("mc.fdc.kanfang.file.is.empty"));
			batch_import_view(el);
			return;
		}
		//name,contact,project_title
		int i = 2;
		List<FDCProject> project_list = null;
		
		try {
			project_list = project_dao.getAllByWxprojectId(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error") + e.getLocalizedMessage());
			batch_import_view(el);
			return;
		}
		List<KanFang> kf_list = null;
		int imported = 0;
		for (List<String> kanfang : kanfang_list) {
			if (kanfang.size() < 3) {
				el.setAttr("msg", String.format(el.i18("mc.fdc.kanfang.lackof.data"), i));
				batch_import_view(el);
				return;
			}
			System.out.println("import:" + kanfang.get(0) + "|" + kanfang.get(1) + "|" + kanfang.get(2));
			String name = kanfang.get(0) == null ? "" : kanfang.get(0).trim();
			String contact = kanfang.get(1) == null ? "" : kanfang.get(1).trim();
			
			KanFang kf = new KanFang();
			kf.setName(name);
			kf.setContact(contact);
			kf.setStatus(KanFangStatus.finish.getValue());
			kf.setType(KanFangType.BOOK.getValue());
			kf.setProgress(KanFangProgress.CLOSED.getValue());
			kf.setCommission(0);
			kf.setCreate_time(Calendar.getInstance().getTime());
			kf.setRemark("批量导入");
			kf.setOn_visit_paid(KanFang.ON_VISIT_PAID);
			kf.setRecommend_paid(KanFang.RECOMMEND_PAID);
			for (FDCProject proj : project_list) {
				System.out.println(proj.getTitle() + "=" + kanfang.get(2).trim());
				if (proj.getTitle().trim().contains(kanfang.get(2).trim())) {
					kf.setProject_id(proj.getId());
					break;
				}
			}
			if (kf.getProject_id() <= 0) {
				el.setAttr("msg", String.format(el.i18("mc.fdc.kanfang.project_title.not.matched"), i));
				batch_import_view(el);
				return;
			}
			try {
				if (!kanfang_dao.hasLogged(wxproject_id,kf.getContact(), kf.getProject_id())) {
					if (kf_list == null) {
						kf_list = new LinkedList<KanFang>();
					}
					kf_list.add(kf);
					imported++;
				}
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg", el.i18("fdc_project.db.error") + e.getLocalizedMessage());
				batch_import_view(el);
				return;
			}
			
			i++;
		}
		
		try {
			if (kf_list != null) {
				kanfang_dao.batch_insert(kf_list);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error") + e.getLocalizedMessage());
			batch_import_view(el);
			return;
		}
		el.setAttr("msg", String.format(el.i18("success_imported"), kanfang_list.size(), imported));
		batch_import_view(el);
	}
	
	private void sales_detail(EventLoader el,long wxproject_id) throws IOException, ServletException {
		Long id = el.getLong("id");
		UserBasic user = null;
		try {
			user = user_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			index(el,wxproject_id);
			return;
		}
		if (user == null) {
			index(el,wxproject_id);
			return;
		}
		List<FDCProject> plist = null;
		try {
			plist = project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		el.setAttr("project_list", plist);
		List<KanFangDetail> rlist = null;
		try {
			rlist = kanfang_dao.getSalesDetailList(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		
		el.setAttr("user_detail", user);
		el.setAttr("rlist", rlist);
		
		el.template("/WEB-INF/template/boss/fdc/kanfang/sales_detail.vm");
	}
	
	private void user_detail(EventLoader el,long wxproject_id) throws IOException, ServletException {
		Long id = el.getLong("id");
		UserBasic user = null;
		try {
			user = user_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			index(el,wxproject_id);
			return;
		}
		if (user == null) {
			index(el,wxproject_id);
			return;
		}
		List<FDCProject> plist = null;
		try {
			plist = project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		el.setAttr("project_list", plist);
		List<KanFangDetail> rlist = null;
		try {
			rlist = kanfang_dao.getRecommandDetailList(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		
		el.setAttr("user_detail", user);
		el.setAttr("rlist", rlist);
		el.template("/WEB-INF/template/boss/fdc/kanfang/user_detail.vm");
	}
	
	private void setting(EventLoader el,long wxproject_id) throws IOException, ServletException {
		String yongjin_return = el.getStr("yongjin_return");
		String recommand_onvisit = el.getStr("recommand_onvisit");
		String yongjin_jingjiren_return = el.getStr("yongjin_jingjiren_return");
		float yongjin_jingjiren_rate = el.getFloat("yongjin_jingjiren_rate");
		float yongjin_old_cus_rate = el.getFloat("yongjin_old_cus_rate");
		int user_black_list_limit = el.getInt("user_black_list_limit");
		String recommand_invite_benifit_rules = el.getStr("recommand_invite_benifit_rules");
		int max_recommand_submit = el.getInt("max_recommand_submit");
		boolean income_for_recommand = el.getBool("income_for_recommand");
		boolean recommand_confirm_benifit = el.getBool("recommand_confirm_benifit");
		float recommand_benifit_value = el.getFloat("recommand_benifit_value");
		boolean kanfang_notify_enable = el.getBool("kanfang_notify_enable");
		String kanfang_notify_email = el.getStr("kanfang_notify_email");
		
		if (!el.paramIsFloat("yongjin_jingjiren_rate")) {
			el.setAttr("msg", el.i18("mc.fdc.yongjin_jingjiren_rate.must.be.float"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if (!el.paramIsFloat("yongjin_old_cus_rate")) {
			el.setAttr("msg", el.i18("mc.fdc.yongjin_old_cus_rate.must.be.float"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if (!el.paramIsInteger("user_black_list_limit")) {
			el.setAttr("msg", el.i18("mc.fdc.user_black_list_limit.must.be.integer"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if (!el.paramIsInteger("max_recommand_submit")) {
			el.setAttr("msg", el.i18("mc.fdc.max_recommand_submit.must.be.integer"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if (!Email.isEmail(kanfang_notify_email)) {
			el.setAttr("msg", String.format(el.i18("mc.email.format.wrong"), kanfang_notify_email));
			view_setting(el,wxproject_id);
			return;
		}
		
		String msg = null;
		try {
			ProjectConfig.update(wxproject_id, "fdc_kanfang.yongjin_return", yongjin_return);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.recommand_onvisit", recommand_onvisit);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.yongjin_jingjiren_return", yongjin_jingjiren_return);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.yongjin_jingjiren_rate", yongjin_jingjiren_rate);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.yongjin_old_cus_rate", yongjin_old_cus_rate);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.user_black_list_limit", user_black_list_limit);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.recommand_invite_benifit_rules", recommand_invite_benifit_rules);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.max_recommand_submit", max_recommand_submit);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.income_for_recommand", income_for_recommand);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.recommand_confirm_benifit", recommand_confirm_benifit);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.recommand_benifit_value", recommand_benifit_value);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.email_notify_enable", kanfang_notify_enable);
			ProjectConfig.update(wxproject_id, "fdc_kanfang.notify_email", kanfang_notify_email);
		} catch (Exception e) {
			e.printStackTrace();
			msg = el.i18("mc.kanfang.default_msg_reply.failured") + ":" + e.getMessage();
		}
		if (msg == null) {
			msg = el.i18("mc.kanfang.setting.success");
		}
		el.setAttr("msg", msg);
		
		view_setting(el,wxproject_id);
	}
	
	private void view_setting(EventLoader el,long wxproject_id) throws IOException, ServletException {
		
		el.setAttr("yongjin_return", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.yongjin_return"));
		el.setAttr("recommand_onvisit", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.recommand_onvisit"));
		el.setAttr("yongjin_jingjiren_return", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.yongjin_jingjiren_return"));
		el.setAttr("yongjin_jingjiren_rate", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.yongjin_jingjiren_rate"));
		el.setAttr("yongjin_old_cus_rate", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.yongjin_old_cus_rate"));
		el.setAttr("user_black_list_limit", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.user_black_list_limit"));
		el.setAttr("recommand_invite_benifit_rules", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.recommand_invite_benifit_rules"));
		el.setAttr("max_recommand_submit", ProjectConfig.getInt(wxproject_id,"fdc_kanfang.max_recommand_submit"));
		el.setAttr("income_for_recommand", ProjectConfig.getBool(wxproject_id,"fdc_kanfang.income_for_recommand"));
		el.setAttr("recommand_confirm_benifit", ProjectConfig.getBool(wxproject_id,"fdc_kanfang.recommand_confirm_benifit"));
		el.setAttr("recommand_benifit_value", ProjectConfig.getFloat(wxproject_id,"fdc_kanfang.recommand_benifit_value"));
		el.setAttr("kanfang_notify_email", ProjectConfig.getStr(wxproject_id,"fdc_kanfang.notify_email"));
		el.setAttr("kanfang_notify_enable", ProjectConfig.getBool(wxproject_id,"fdc_kanfang.email_notify_enable"));
		
		el.template("/WEB-INF/template/boss/fdc/kanfang/setting.vm");
	}
	
	private void update(EventLoader el,Customer adm) throws IOException, ServletException {
		long id = el.getAndSetLong("id");
		KanFang kanfang = null;
		try {
			kanfang = kanfang_dao.get(id);
			if (kanfang == null) {
				el.setAttr("msg", el.i18("mc.kanfang.not.exists"));
				index(el,adm.getWxprojectID());
				return;
			}
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			e.printStackTrace();
			index(el,adm.getWxprojectID());
			return;
		}
		
		FDCProject project = null;
		try {
			project = project_dao.get(kanfang.getProject_id());
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			e.printStackTrace();
			index(el,adm.getWxprojectID());
			return;
		}
		
		if (kanfang.getSalesman() == 0 && el.getLong("salesman") > 0) {
			el.getAndSetLong("salesman");
		}
		
		int recommend_paid = kanfang.getRecommend_paid();
		int on_visit_paid = kanfang.getOn_visit_paid();
		String gohousedate = el.getAndSetStr("gohousedate");
		String reason = el.getStr("reason");
		String remark_append = el.getStr("remark_append");
		int status = el.getAndSetInt("status", -1);
		el.setParam("update_date", new Date(System.currentTimeMillis()));
		kanfang.setStatus(status);
		String msg = validate(el, reason, gohousedate, status);
		if (StringHelper.isNotNull(msg)) {
			el.setAttr("msg", msg);
			index(el,adm.getWxprojectID());
			return;
		}
		
		msg = updateAppendStatus(el, status, reason, remark_append);
		
		if (StringHelper.isNotNull(msg)) {
			el.setAttr("msg", msg);
			index(el,adm.getWxprojectID());
			return;
		}
		
		msg = updateProgress(el, status);
		if (StringHelper.isNotNull(msg)) {
			el.setAttr("msg", msg);
			index(el,adm.getWxprojectID());
			return;
		}
		
		try {
			kanfang_dao.update(el.getParams());
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			e.printStackTrace();
			index(el,adm.getWxprojectID());
			return;
		}
		
		msg = insertFlow(el, id, reason, status, 0);
		
		if (StringHelper.isNotNull(msg)) {
			el.setAttr("msg", msg);
			index(el,adm.getWxprojectID());
			return;
		}
		
		if (msg == null) {
			el.setAttr("msg", el.i18("mc.kanfang.setting.success"));
			try {
				customer_update_notify(el,adm.getWxprojectID(), kanfang, project, reason);
			} catch (SQLException e) {
				el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
				e.printStackTrace();
				index(el,adm.getWxprojectID());
				return;
			}
		}
		
		if (msg == null) {
			el.setAttr("msg", el.i18("mc.kanfang.setting.success"));
			try {
				customer_status_change_apply(el,adm.getWxprojectID(), id, status, recommend_paid, on_visit_paid, kanfang, project);
			} catch (SQLException e) {
				el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
				e.printStackTrace();
				index(el,adm.getWxprojectID());
				return;
			}
		}
		
		index(el,adm.getWxprojectID());
	}
	
	private String customer_status_change_apply(EventLoader el,long wxproject_id, long kf_id, int status, int recommend_paid, int on_visit_paid, KanFang kanfang, FDCProject project) throws SQLException {
		if (status == KanFangStatus.return_cash.getValue()&& recommend_paid == KanFang.RECOMMEND_NOT_PAID) {
			kanfang.setCommission(el.getFloat("cash"));
			kanfang_dao.update_recommend_paid(kf_id, el.getFloat("cash"));
			return offerCash(el,wxproject_id, kanfang, project, kanfang.getCommission(), ProjectConfig.getStr(wxproject_id,"fdc_kanfang.yongjin_return"));
		} else if (status == KanFangStatus.ready_to_sign.getValue() && on_visit_paid == KanFang.ON_VISIT_NOT_PAID) {
			return offerOnvisitCash(el,wxproject_id, kanfang, project, ProjectConfig.getStr(wxproject_id,"fdc_kanfang.recommand_onvisit"));
		} else if (status ==KanFangStatus.black_list.getValue()) {
			user_dao.imcreate_black_list(kanfang.getRecommend_user());
		}
		return null;
	}
	
	private void customer_update_notify(EventLoader el,long wxproject_id, KanFang kanfang, FDCProject project, String reason) throws SQLException {
		UserWeiXinInfo user_weixin = weixin_dao.getByUserId(kanfang.getRecommend_user());
		
		StringBuilder notifyMessage = new StringBuilder("客户最新状态:" + kanfang.getStatusDesc());
		if (kanfang.getSalesman() == 0 && el.getLong("salesman") > 0) {
			UserBasic salesman = user_dao.getById(el.getLong(""));
			if (salesman != null) {
				notifyMessage.append("。销售已分配-").append(salesman.getName());
			}
		}
		
		if (user_weixin != null && project != null) {
			change_status_reply(wxproject_id,notifyMessage.toString(), user_weixin.getId(), project, kanfang, reason + "\n如有疑问,请致电客服.");
		}
		
		if (kanfang.getRecommend_user() != el.getLong("salesman") && el.getLong("salesman") > 0) {
			UserWeiXinInfo salesmanWeixinInfo = weixin_dao.getByUserId(el.getLong("salesman"));
			
			if (salesmanWeixinInfo != null && project != null) {
				change_status_reply(wxproject_id,notifyMessage.toString(), salesmanWeixinInfo.getId(), project, kanfang, reason + "\n如有疑问,请致电客服.");
			}
		}
	}
	
	/**
	 * 
	 * 客户状态变更通知
	 * 
	 * {{first.DATA}}\n客户姓名:{{customName.DATA}}\n客户电话:{{customPhone.DATA}}\n
	 * 推荐楼盘:{{reportBuilding.DATA}}\n
	 * 推荐时间:{{reportTime.DATA}}\n{{change.DATA}}
	 * 时间:{{changeTime.DATA}}\n{{remark.DATA}}
	 * 
	 * */
	public static void change_status_reply(long wxproject_id,String first_msg, String ropenid, FDCProject project, KanFang kanfang, String _remark) {
		if (StringHelper.isNull(ropenid))
			return;
		JObject params = new JObject();
		JObject first = new JObject();
		first.put("value", first_msg + "\n");
		first.put("color", ReplyMsg.RED);
		params.put("first", first);
		
		JObject customName = new JObject();
		customName.put("value", kanfang.getName());
		customName.put("color", ReplyMsg.BLUE);
		params.put("customName", customName);
		
		JObject customPhone = new JObject();
		customPhone.put("value", kanfang.getContact());
		customPhone.put("color", ReplyMsg.BLUE);
		params.put("customPhone", customPhone);
		
		JObject reportBuilding = new JObject();
		reportBuilding.put("value", project.getTitle());
		reportBuilding.put("color", ReplyMsg.LIGHT_BLACK);
		params.put("reportBuilding", reportBuilding);
		
		JObject reportTime = new JObject();
		reportTime.put("value", kanfang.getGohousedate());
		reportTime.put("color", ReplyMsg.BLUE);
		params.put("reportTime", reportTime);
		
		JObject change = new JObject();
		change.put("value", "");
		change.put("color", ReplyMsg.BLUE);
		params.put("change", change);
		
		JObject changeTime = new JObject();
		changeTime.put("value", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		changeTime.put("color", ReplyMsg.BLUE);
		params.put("changeTime", changeTime);
		
		JObject remark = new JObject();
		remark.put("value", _remark);
		remark.put("color", ReplyMsg.BLUE);
		params.put("remark", remark);
		
		ReplyMsg msg = new ReplyMsg();
		msg.setMsg_link("");
		msg.setOpenid(ropenid);
		msg.setWxproject_id(wxproject_id);
		msg.setTemplate_id(ProjectConfig.getStr(wxproject_id,"fdc_kanfang.customer_change_template_msg_id"));
		msg.setTopcolor(ReplyMsg.BLUE);
		msg.setData_params(params);
		TemplateReply.asyReply(msg);
	}
	
	/**
	 * 
	 {{first.DATA}} 客户姓名:{{customName.DATA}} 客户电话:{{customPhone.DATA}}
	 * 推荐楼盘:{{reportBuilding.DATA}} 推荐时间:{{reportTime.DATA}}
	 * 成交金额:{{signAmount.DATA}} 成交时间:{{signTime.DATA}}
	 * 佣金金额:{{commissionAmount.DATA}} 结佣时间:{{commissionTime.DATA}}
	 * {{remark.DATA}}
	 * 
	 * */
	public static void recieve_msg(long wxproject_id,String title, long user_id, KanFang kanfang, FDCProject project, float yongjin, String _remark) {
		if (project == null) {
			return;
		}
		UserWeiXinInfo weixin = null;
		try {
			weixin = weixin_dao.getByUserId(user_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (weixin == null || StringHelper.isNull(weixin.getId())) {
			return;
		}
		KanFangFlow kanfang_flow = null;
		try {
			kanfang_flow = kanfang_flow_dao.getFlowByStatus(kanfang.getId(),KanFangStatus.sign_success.getValue());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		JObject params = new JObject();
		JObject first = new JObject();
		first.put("value", title + "\n");
		first.put("color", ReplyMsg.BLUE);
		params.put("first", first);
		
		JObject customName = new JObject();
		customName.put("value", kanfang.getName());
		customName.put("color", ReplyMsg.BLUE);
		params.put("customName", customName);
		
		JObject customPhone = new JObject();
		customPhone.put("value", kanfang.getContact());
		customPhone.put("color", ReplyMsg.BLUE);
		params.put("customPhone", customPhone);
		
		JObject reportBuilding = new JObject();
		reportBuilding.put("value", project.getTitle());
		reportBuilding.put("color", ReplyMsg.BLUE);
		params.put("reportBuilding", reportBuilding);
		
		JObject reportTime = new JObject();
		reportTime.put("value", kanfang.getCreate_time_str());
		reportTime.put("color", ReplyMsg.BLUE);
		params.put("reportTime", reportTime);
		
		if (kanfang_flow != null) {
			JObject signTime = new JObject();
			signTime.put("value", new Date(kanfang_flow.getOper_timestamp()).toLocaleString());
			signTime.put("color", ReplyMsg.BLUE);
			params.put("signTime", signTime);
		}
		
		JObject commissionAmount = new JObject();
		commissionAmount.put("value", yongjin);
		commissionAmount.put("color", ReplyMsg.RED);
		params.put("commissionAmount", commissionAmount);
		
		JObject commissionTime = new JObject();
		commissionTime.put("value", Calendar.getInstance().getTime().toLocaleString());
		commissionTime.put("color", ReplyMsg.RED);
		params.put("commissionTime", commissionTime);
		
		JObject remark = new JObject();
		remark.put("value", _remark);
		remark.put("color", ReplyMsg.BLUE);
		params.put("remark", remark);
		
		ReplyMsg msg = new ReplyMsg();
		msg.setMsg_link("");
		msg.setOpenid(weixin.getId());
		msg.setWxproject_id(wxproject_id);
		msg.setTemplate_id(ProjectConfig.getStr(wxproject_id,"fdc_cash_flow.receive_yongjin_msg_template_id"));
		msg.setTopcolor(ReplyMsg.BLUE);
		msg.setData_params(params);
		TemplateReply.asyReply(msg);
	}
	
	public static String offerOnvisitCash(EventLoader el,long wxproject_id, KanFang kanfang, FDCProject project, String reason) {
		float cash = 0;
		FDCAgent user = null;
		
		try {
			user = fdcuser_dao.getById(kanfang.getRecommend_user());
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage();
		}
		
		if (user == null) {
			return el.i18("mc.kanfang.user.not.exists");
		}
		
		if (StringHelper.equals(user.getType(),UserType.manager.name())) {
			cash = project.getManager_on_visit_bonus();
		} else {
			cash = project.getOld_cus_on_visit_bonus();
		}
		
		try {
			kanfang_dao.update_on_visit_paid(kanfang.getId(), cash);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage();
		}
		
		return offerCash(el,wxproject_id, kanfang, project, cash, reason);
	}
	
	private String validate(EventLoader el, String reason, String gohousedate, int status) {
		if (reason.length() > Keys.getInt("kanfang.flow_remark_length_in_backend")) {
			
			return String.format(el.i18("mc.kanfang.flow.remark.length.exceed"), Keys.getInt("kanfang.flow_remark_length_in_backend"));
		}
		if (gohousedate.length() > Keys.getInt("kanfang.gohousedate_length_in_backend")) {
			
			return String.format(el.i18("mc.kanfang.gohousedate.length.exceed"), Keys.getInt("kanfang.gohousedate_length_in_backend"));
		}
		if (status == -1) {
			return el.i18("mc.kanfang.status.need");
		}
		return null;
	}
	
	public static String updateAppendStatus(EventLoader el, int status, String reason, String remark_append) {
		String status_desc = KanFangStatus.getDesc(status);
		if (status_desc == null) {
			return el.i18("mc.kanfang.status.not.found");
		}
		remark_append = "[" + Calendar.getInstance().getTime().toLocaleString() + "][状态更新=>" + status_desc + "]" + reason.trim() + "<br/>" + remark_append;
		
		el.setParam("remark_append", remark_append);
		return null;
	}
	
	private String updateProgress(EventLoader el, int status) {
		if (status == KanFangStatus.sign_success.getValue()) {
			el.setParam("progress", KanFangProgress.CLOSED.getValue());
		} else if (status == KanFangStatus.failed_close.getValue()) {
			el.setParam("progress", KanFangProgress.CLOSED.getValue());
		} else if (status == KanFangStatus.return_cash.getValue()) {
			if (!el.paramIsFloat("cash") || el.getFloat("cash") < 0) {
				return String.format(el.i18("mc.kanfang.cash.format.is.not.correct"), el.getStr("cash"));
			}
			el.setParam("progress", KanFangProgress.CASH_RETURN.getValue());
		} else if (status == KanFangStatus.finish.getValue()) {
			el.setParam("progress", KanFangProgress.CLOSED.getValue());
		} else if (status == KanFangStatus.black_list.getValue()) {
			el.setParam("progress", KanFangProgress.CLOSED.getValue());
		} else if (status == KanFangStatus.ready_to_sign.getValue()) {
			el.setParam("progress", KanFangProgress.PROGRESS.getValue());
		} else {
			el.setParam("progress", KanFangProgress.PROGRESS.getValue());
		}
		return null;
	}
	
	public static String insertFlow(EventLoader el, long kf_id, String remark, int status, long operId) {
		KanFangFlow kff = new KanFangFlow();
		kff.setCurrent_status(status);
		kff.setKf_id(kf_id);
		kff.setOper(operId);
		kff.setOper_timestamp(System.currentTimeMillis());
		kff.setRemark(remark);
		
		try {
			kanfang_flow_dao.insert(kff);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage();
		}
		return null;
	}
	
	private static String offerCash(EventLoader el,long wxproject_id, KanFang kanfang, FDCProject project, float cash, String reason) {
		
		long from_user = kanfang.getRecommend_user();
		if (cash <= 0) {
			return null;
		}
		CashFlow mycash = new CashFlow();
		mycash.setCash(cash);
		mycash.setFrom_user_id(0);
		mycash.setReason(reason);
		mycash.setTimestamp(System.currentTimeMillis());
		mycash.setUser_id(from_user);
		mycash.setFlow_in(CashFlow.FLOW_IN);
		mycash.setIn_status(CashFlow.IN_STATUS_IN);
		try {
			cash_flow_dao.insert(mycash);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage();
		}
		
		recieve_msg(wxproject_id,"佣金收入(推荐成功交易奖金)", from_user, kanfang, project, cash, reason);
		
		// 获得我的推荐者
		FDCAgent user = null;
		try {
			user = fdcuser_dao.getMyInvitor(from_user);
		} catch (SQLException e1) {
			e1.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error") + ":" + e1.getLocalizedMessage();
		}
		if (user == null) {
			return null;
		}
		float jjr_cash = cash;
		if (StringHelper.equals(user.getType(), UserType.manager.name())) {
			jjr_cash = jjr_cash * ProjectConfig.getFloat(wxproject_id,"fdc_kanfang.yongjin_jingjiren_rate");
		} 
		if(StringHelper.equals(user.getType(), UserType.old.name())){
			jjr_cash = jjr_cash * ProjectConfig.getFloat(wxproject_id,"fdc_kanfang.yongjin_old_cus_rate");
		}
		if(jjr_cash<=0){
			return null;
		}
		CashFlow jjr = new CashFlow();
		jjr.setCash(jjr_cash);
		jjr.setFrom_user_id(from_user);
		jjr.setReason(reason + "(经纪人)");
		jjr.setTimestamp(System.currentTimeMillis());
		jjr.setUser_id(user.getId());
		jjr.setFlow_in(CashFlow.FLOW_IN);
		jjr.setIn_status(CashFlow.IN_STATUS_IN);
		try {
			cash_flow_dao.insert(jjr);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("mc.kanfang.internal.server.error:") + ":" + e.getLocalizedMessage();
		}
		recieve_msg(wxproject_id,"佣金收入(来自我的经纪人)", user.getId(), kanfang, project, jjr_cash, reason);
		
		return null;
	}
	
	private String buildWhereCondition(EventLoader el) {
		StringBuilder query = new StringBuilder();
		
		if (el.paramExists("_type") && el.getInt("_type", -1) != -1) {
			query.append(" and fdc_kanfang.type=").append(el.getInt("_type", -1));
			el.setAttr("_type", el.getLong("_type", -1));
		}
		if (el.paramExists("_progress") && el.getInt("_progress", -1) != -1) {
			query.append(" and fdc_KanFangProgress=").append(el.getInt("_progress", -1));
			el.setAttr("_progress", el.getLong("_progress", -1));
		} else {
			query.append(" and fdc_kanfang.status=").append(el.getInt("_status", -1));
			el.setAttr("_status", el.getLong("_status", -1));
		}
		
		if (el.paramExists("_project_id") && el.getInt("_project_id", -1) != -1) {
			System.out.println("project_id:" + el.getInt("_project_id"));
			query.append(" and fdc_kanfang.project_id=").append(el.getLong("_project_id"));
			el.setAttr("_project_id", el.getLong("_project_id"));
		}
		return query.toString();
	}
	
	private void index(EventLoader el,long wxproject_id) throws IOException, ServletException {
		String name = el.param("name", "", "utf-8");
		String phone = el.param("phone", "", "utf-8");
		int page = el.getInt("page", 1);
		int size = Keys.getInt("sys_page_size");
		int total = 0;
		
		String whereCondition = buildWhereCondition(el);
		String msg = null;
		try {
			if (StringHelper.isNull(name) && StringHelper.isNull(phone)) {
				total = kanfang_dao.countByWhereCondition(wxproject_id,whereCondition);
			} else if (StringHelper.isNotNull(name)) {
				total = kanfang_dao.countSearchByWhereCondition(wxproject_id,whereCondition, name);
				phone = "";
			} else if (StringHelper.isNotNull(phone)) {
				total = kanfang_dao.countByWhereConditionAndContact(wxproject_id,whereCondition, phone);
				name = "";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = el.i18("kanfang.yuyue.db.failure");
			el.setAttr("msg", msg);
		}
		
		PageData page_data = new PageData<FDCAgentDetail>(page, total, size, null);
		
		List<KanFang> list = null;
		List<FDCAgent> salesman=null;
		try {
			if (StringHelper.isNull(name) && StringHelper.isNull(phone)) {
				list = kanfang_dao.getByWhereConditions(wxproject_id,whereCondition, page_data.getStart(), size);
			} else if (StringHelper.isNotNull(name)) {
				list = kanfang_dao.searchByWhereCondition(wxproject_id,whereCondition, name, page_data.getStart(), size);
			} else if (StringHelper.isNotNull(phone)) {
				list = kanfang_dao.searchByWhereConditionAndContact(wxproject_id,whereCondition, phone, page_data.getStart(), size);
			}
			salesman=fdcuser_dao.getAllSalesmanByStatus(wxproject_id,"ok");
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			el.setAttr("msg", msg);
		}
		
		page_data.setData(list);
		
		List<FDCProject> plist = null;
		try {
			plist = project_dao.getAllByWxprojectId(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
		}
		
		el.setAttr("project_list", plist);
		
		el.setAttr("salesList", salesman);
		el.setAttr("page_data", page_data);
		el.setAttr("name", name);
		el.setAttr("phone", phone);
		el.setAttr("name_encode", URLEncoder.encode(name, "utf-8"));
		el.template("/WEB-INF/template/boss/fdc/kanfang/index.vm");
	}
	

	
}
